package com.os.osframe.scaffold.velocity;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.*;

/**
 * Created by wangchun on 18/4/28.
 */
public class VelocityParse {
    protected static VelocityParse velocityParse;

    /**
     * 获取解析函数的单例模式
     * @return
     */
    public static VelocityParse getInstance(){
        if(velocityParse==null){
            velocityParse=new VelocityParse();
            velocityParse.initVelocity();
            return velocityParse;
        }
        return velocityParse;
    }
    protected VelocityEngine velocityEngine;

    /**
     * 初始化模板引擎
     * @return
     */
    public VelocityEngine initVelocity(){
        velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        velocityEngine.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        velocityEngine.init();

        return velocityEngine;
    }

    /**
     * 根据模板解析
     * @param tempPath 模板路径
     * @param paramMap 参数
     * @return
     */
    public String parseTemplate(String tempPath,Map paramMap){
        if(velocityEngine==null || tempPath==null || "".equals(tempPath.trim())){
            return null;
        }
        Template t = velocityEngine.getTemplate(tempPath);
        VelocityContext ctx = new VelocityContext();
        if(paramMap!=null && !paramMap.isEmpty()){
            Iterator it=paramMap.keySet().iterator();
            while(it.hasNext()){
                String key=(String)it.next();
                ctx.put(key, paramMap.get(key));
            }
        }

        StringWriter sw = new StringWriter();
        t.merge(ctx, sw);
        return sw.toString();
    }
}
